package com.yaorange.common.utils;


import com.alibaba.fastjson2.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class SmsUtils {

    private static final String ACCESS_KEY_ID = "LTAI5t8QTjjzgubwHE5xFQHv";
    private static final String ACCESS_KEY_SECRET = "pMu1huWs6kia747GegY0L1LfVgIZC9";
    private static final String SIGN_NAME = "阿里云短信测试";
    private static final String TEMPLATE_CODE = "SMS_154950909";

    /**
     * 发送短信验证码
     * @param mobilePhone 手机号
     * @param code 验证码
     */
    public static void sendSms(String mobilePhone, String code) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-qingdao")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", code);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(SIGN_NAME)
                .templateCode(TEMPLATE_CODE)
                .phoneNumbers(mobilePhone)
                .templateParam(JSON.toJSONString(templateParam))
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        response.thenAccept(resp -> {
            log.info("短信发送结果: {}", new Gson().toJson(resp));
        }).exceptionally(throwable -> {
            log.error("短信发送失败: {}", throwable.getMessage());
            return null;
        });

//        client.close();
    }
}
